'use strict';

exports.main = async (event, context) => {
  const db = uniCloud.database();
  const { paymentId, reason, adminId } = event;

  if (!paymentId || !reason) {
    return {
      code: 400,
      msg: '缺少必要参数',
      data: null
    };
  }

  try {
    const paymentCollection = db.collection('payment_records');
    
    // 获取支付记录
    const paymentResult = await paymentCollection.doc(paymentId).get();
    if (!paymentResult.data || paymentResult.data.length === 0) {
      return {
        code: 404,
        msg: '支付记录不存在',
        data: null
      };
    }

    const payment = paymentResult.data[0];

    // 检查支付状态
    if (payment.status !== 'success') {
      return {
        code: 400,
        msg: '只能对支付成功的订单进行退款',
        data: null
      };
    }

    // 检查是否已经退款
    if (payment.refund_status === 'refunded') {
      return {
        code: 400,
        msg: '该订单已经退款',
        data: null
      };
    }

    // 创建退款记录
    const refundCollection = db.collection('refund_records');
    const refundResult = await refundCollection.add({
      payment_id: paymentId,
      original_payment_id: payment.payment_id,
      user_id: payment.user_id,
      amount: payment.amount,
      refund_reason: reason,
      admin_id: adminId || 'admin',
      status: 'processing',
      create_time: new Date()
    });

    // 更新支付记录状态
    await paymentCollection.doc(paymentId).update({
      refund_status: 'processing',
      refund_reason: reason,
      refund_admin: adminId || 'admin',
      refund_time: new Date(),
      update_time: new Date()
    });

    // 如果是钱包支付，直接退回用户余额
    if (payment.payment_method === 'wallet') {
      try {
        // 调用积分管理云函数增加用户余额
        const balanceResult = await uniCloud.callFunction({
          name: 'userPointsManager',
          data: {
            action: 'add',
            userId: payment.user_id,
            amount: payment.amount,
            type: 'refund',
            description: `订单退款：${reason}`,
            relatedId: paymentId
          }
        });

        if (balanceResult.result && balanceResult.result.code === 200) {
          // 更新退款状态为成功
          await refundCollection.doc(refundResult.id).update({
            status: 'success',
            processed_time: new Date()
          });

          await paymentCollection.doc(paymentId).update({
            refund_status: 'refunded'
          });

          // 发送退款成功通知
          const messageCollection = db.collection('system_messages');
          await messageCollection.add({
            user_id: payment.user_id,
            type: 'refund',
            title: '退款成功通知',
            content: `您的订单 ${payment.payment_id} 已成功退款 ¥${payment.amount}，款项已退回您的钱包余额。`,
            create_time: new Date(),
            read: false
          });
        }
      } catch (balanceError) {
        console.error('钱包退款失败:', balanceError);
        // 退款失败，更新状态
        await refundCollection.doc(refundResult.id).update({
          status: 'failed',
          error_message: balanceError.message || '退款处理失败'
        });
      }
    } else {
      // 对于第三方支付（微信、支付宝），需要调用相应的退款接口
      // 这里简化处理，实际应该调用相应的第三方退款API
      console.log(`第三方支付退款需要人工处理：${payment.payment_method}`);
      
      // 发送通知给用户，告知退款正在处理
      const messageCollection = db.collection('system_messages');
      await messageCollection.add({
        user_id: payment.user_id,
        type: 'refund',
        title: '退款申请已受理',
        content: `您的退款申请已受理，订单 ${payment.payment_id} 退款金额 ¥${payment.amount}，预计3-7个工作日到账。`,
        create_time: new Date(),
        read: false
      });
    }

    // 记录管理员操作日志
    const auditLogCollection = db.collection('audit_logs');
    await auditLogCollection.add({
      target_type: 'payment',
      target_id: paymentId,
      action: 'refund',
      reason: reason,
      admin_id: adminId || 'admin',
      create_time: new Date(),
      extra_info: {
        amount: payment.amount,
        payment_method: payment.payment_method,
        refund_id: refundResult.id
      }
    });

    return {
      code: 200,
      msg: '退款处理成功',
      data: {
        refund_id: refundResult.id,
        payment_id: paymentId,
        amount: payment.amount,
        payment_method: payment.payment_method,
        auto_processed: payment.payment_method === 'wallet'
      }
    };
  } catch (error) {
    console.error('退款处理失败:', error);
    return {
      code: 500,
      msg: '退款处理失败',
      data: null
    };
  }
};
